package com.haust.leyou.controller;

import com.haust.leyou.pojo.User;
import com.haust.leyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @Auther: csp1999
 * @Date: 2020/12/17/21:14
 * @Description:
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户数据校验是否可用（用户是否存在）
     *
     * @param data 要校验的数据
     * @param type 要校验的数据类型：1，用户名；2，手机；
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUser(@PathVariable("data") String data,
                                             @PathVariable("type") Integer type) {
        Boolean bool = userService.checkUser(data, type);

        if (bool == null) {
            // 400 参数有误
            return ResponseEntity.badRequest().build();
        }

        // 200：校验成功 true：可用/false：不可用
        return ResponseEntity.ok(bool);
    }

    /**
     * 发送验证码
     *
     * @param phone 接收者的手机号
     * @return
     */
    @PostMapping("/sendCode")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone) {

        // 发送验证码
        userService.sendVerifyCode(phone);

        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 用户注册
     *
     * @param user 用户
     * @param code 验证码
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code") String code) {

        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户信息
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<User> queryUser(@RequestParam("username") String username,
                                          @RequestParam("password") String password) {
        // 根据用户名和密码查询用户信息
        User user = userService.queryUser(username, password);

        if (user == null) {
            return ResponseEntity.badRequest().build();
        }

        return ResponseEntity.ok(user);
    }
}
